package com.rdc.jiajiadictionary.translate;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.rdc.jiajiadictionary.R;


public class TranslateActivity extends AppCompatActivity implements View.OnClickListener{
    private EditText translateEt;
    private FrameLayout backIv;
    private ImageView resetInputIv;
    private HistoryFragment historyFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.translate_activity);
        backIv = (FrameLayout) findViewById(R.id.iv_back);
        resetInputIv = (ImageView) findViewById(R.id.iv_resetInput);
        translateEt = (EditText) findViewById(R.id.et_translate);

        //创建HistoryFragment对象，实现点击历史记录子项时更换碎片的接口
        historyFragment =  new HistoryFragment(new HistoryFragment.ReplaceFragmentCallBack() {
            @Override
            public void onClickReplace(String text) {
                hideSoftInputFromWindow(translateEt);
                translateEt.setText(text);
                TranslateFragment translateFragment = new TranslateFragment(text);
                replaceFragment(translateFragment);
            }
        });
        replaceFragment(historyFragment);

        //自动弹出软键盘
        showSoftInputFromWindow(translateEt);

        //设置软键盘回车键的点击监听，点击时进行碎片更换，获取单词的网络获取翻译
        translateEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if( !TextUtils.isEmpty(v.getText())){
                    if(actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) ){
                        hideSoftInputFromWindow(translateEt);
                        TranslateFragment translateFragment = new TranslateFragment(v.getText().toString());
                        replaceFragment(translateFragment);
                        return true;
                    }
                }

                return false;
            }
        });
        //监听EditText的输入
        translateEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //EditText没有输入内容时，清除图标不显示
                if (translateEt.getText().length() >= 1){
                    resetInputIv.setVisibility(View.VISIBLE);
                } else{
                    resetInputIv.setVisibility(View.INVISIBLE);
                    replaceFragment(historyFragment);

                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        backIv.setOnClickListener(this);
        resetInputIv.setOnClickListener(this);
    }

    /**
     * 碎片的更换显示
     * @param fragment
     */
    private void replaceFragment(Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.translate_fragment_container, fragment);
        transaction.commit();
    }

    /**
     * 获取EditText焦点并弹出软件盘
     * @param editText
     */
    public void showSoftInputFromWindow(EditText editText){
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        editText.postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm= (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(editText, 0);
            }
        }, 200);
    }

    /**
     * 移除焦点，隐藏软键盘
     * @param editText
     */
    public void hideSoftInputFromWindow(EditText editText){
        editText.clearFocus();
        InputMethodManager imm= (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editText.getWindowToken(),0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_resetInput:
                //点击EditText清除图标时，清除输入内容，显示历史搜索
                translateEt.setText("");
                resetInputIv.setVisibility(View.INVISIBLE);
                replaceFragment(historyFragment);
                showSoftInputFromWindow(translateEt);

        }
    }

}